package main

import (
	"fmt"
	"log"
	"time"

	"go.etcd.io/bbolt"
)

func main() {
	db, err := bbolt.Open("timeseries.db", 0755, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// 模拟数据写入
	err = db.Update(func(tx *bbolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists([]byte("sensor_data"))
		if err != nil {
			return err
		}

		// 写入过去一周的数据
		now := time.Now()
		for i := 0; i < 100; i++ {
			timestamp := now.Add(-time.Duration(i) * time.Hour) // 每小时一个数据点
			key := []byte(fmt.Sprintf("%d", timestamp.UnixNano()))
			value := []byte(fmt.Sprintf("SensorValue: %d", i))
			if err := bucket.Put(key, value); err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}

	// 读取当前数据
	currentTime := time.Now().UnixNano()
	readCurrentData(db, currentTime)

	// 读取本周数据
	readWeeklyData(db)
}

// 按主键读取当前数据
func readCurrentData(db *bbolt.DB, key int64) {
	err := db.View(func(tx *bbolt.Tx) error {
		bucket := tx.Bucket([]byte("sensor_data"))
		if bucket == nil {
			return fmt.Errorf("bucket not found")
		}

		data := bucket.Get([]byte(fmt.Sprintf("%d", key)))
		if data == nil {
			fmt.Println("No data found for the given key.")
			return nil
		}

		fmt.Printf("Current Data: Key = %d, Value = %s\n", key, data)
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}

// 读取本周数据
func readWeeklyData(db *bbolt.DB) {
	err := db.View(func(tx *bbolt.Tx) error {
		bucket := tx.Bucket([]byte("sensor_data"))
		if bucket == nil {
			return fmt.Errorf("bucket not found")
		}

		// 获取本周的起止时间
		now := time.Now()
		weekStart := now.AddDate(0, 0, -int(now.Weekday())) // 本周一
		weekStartKey := []byte(fmt.Sprintf("%d", weekStart.UnixNano()))
		weekEndKey := []byte(fmt.Sprintf("%d", now.UnixNano()))

		// 范围扫描
		cursor := bucket.Cursor()
		for k, v := cursor.Seek(weekStartKey); k != nil && string(k) <= string(weekEndKey); k, v = cursor.Next() {
			fmt.Printf("Weekly Data: Key = %s, Value = %s\n", k, v)
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
